package org.cug.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import jakarta.validation.constraints.Pattern;
import org.cug.pojo.Result;
import org.cug.pojo.User;
import org.cug.service.UserService;
import org.cug.utils.JwtUtil;
import org.cug.utils.Md5Util;
import org.cug.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @author gongshihao
     * @param username 用户名
     * @param password 密码
     * @return
     * @state 已测验
     */

    //用户注册
    @Operation(summary = "用户注册", description = "根据用户名和密码注册用户")
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^.{5,16}$") @RequestParam String username,
                           @Pattern(regexp = "^.{5,16}$")@RequestParam String password)
    {
        //查询用户是否重复
        User u=userService.findByUserName(username);
        if(u==null)
        {
            //没有占用,立即注册
            userService.register(username,password);
        }else {
            return Result.error("用户名已被占用");
        }
        return Result.success();
    }

    /**
     * @author gongshihao
     * @param username 用户名
     * @param password 密码
     * @return
     * @state 已测验
     */

    //用户登录
    @Operation(summary = "用户登录", description = "通过用户名和密码进行登录,同时返回jwt令牌",
            parameters = {
                    @Parameter(name = "username", description = "用户名", required = true, example = "admin"),
                    @Parameter(name = "password", description = "密码", required = true, example = "1234567")
            }
    )
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^.{5,16}$") @RequestParam String username,
                                @Pattern(regexp = "^.{5,16}$") @RequestParam String password) {
        //判断用户
        User u = userService.findByUserName(username);
        if (u == null) {
            return Result.error("用户名错误");
        }
        //判断密码
        if (Md5Util.getMD5String(password).equals(u.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            String token = JwtUtil.genToken(claims);
            //token存储进入redis当中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 3, TimeUnit.DAYS); //token字母作为键，token作为值,并且有效期和token的时效相同都为三天
            System.out.println("Stored Token: " + token); // 添加日志
            return Result.success(token);
        }
        return Result.error("密码错误");
    }


    /**
     * {@code @author} gongshihao
     * @return
     * @state 已测验
     */

    //从token中获取用户的信息
    @GetMapping("/userInfo")
    @Operation(summary = "获取用户信息", description = "返回用户详细信息"
    )
    public Result<User> userInfo() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User u = userService.findByUserName(username);
        return Result.success(u);
    }

    /**
     * {@code @author} gongshihao
     * @param u 用户实体类
     * @return 封装类
     * @state 已测验
     */
    //更新用户数据
    @PutMapping("/update")
    //@RequestBody 将前端传回来的json字符串转换为一个实体类对象
    public Result update(@RequestBody @Validated User u)
    {
        userService.update(u);
        return Result.success();
    }

    /**
     * @author gongshihao
     * @param avatarUrl 用户图片地址
     * @return
     * @state 未测验
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl)
    {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }


    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        // 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        // 是否有非空数据
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        // 本地线程获取
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User loginuser = userService.findByUserName(username);

        // 原密码是否准确
        if (!loginuser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码不准确");
        }

        // 新旧密码是否一致
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的新密码不一致");
        }

        // 更新密码
        userService.updatePwd(Md5Util.getMD5String(newPwd));

        // 返回成功响应
        Result result = Result.success();

        // 删除Token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return result;
    }
}
